package com.lord.otter.component.infrastructure.retry.config;

import com.lord.otter.component.infrastructure.retry.executor.HttpExecutorFacade;
import com.lord.otter.component.infrastructure.retry.executor.RestTemplateExecutor;
import com.lord.otter.component.infrastructure.retry.repository.HttpRetryTaskMybatisRepository;
import com.lord.otter.component.infrastructure.retry.repository.HttpRetryTaskRepository;
import com.lord.otter.component.infrastructure.retry.strategy.AbstractExceptionHandler;
import com.lord.otter.component.infrastructure.retry.strategy.DefaultExceptionHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

@Configuration
public class HttpRetryConfig {

    @Bean
    @ConditionalOnMissingBean(RestTemplate.class)
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder
                .setConnectTimeout(Duration.ofSeconds(5))
                .setReadTimeout(Duration.ofSeconds(10))
                .build();
    }

    /**
     * 没有其他 异常处理 实现时加载 默认异常处理
     *
     * @author lord
     * 2025/9/5 23:34
     */
    @Bean
    @ConditionalOnMissingBean(AbstractExceptionHandler.class)
    public AbstractExceptionHandler exceptionHandler() {
        return new DefaultExceptionHandler();
    }


    /**
     * 没有其他 请求执行器 实现时加载 RestTemplateExecutor
     *
     * @author lord
     * 2025/9/5 23:34
     */
    @Bean
    @ConditionalOnMissingBean(HttpExecutorFacade.class)
    public HttpExecutorFacade executor(RestTemplate restTemplate) {
        return new RestTemplateExecutor(restTemplate);
    }

    /**
     * 没有其他 任务仓储实现时加载 HttpRetryTaskMybatisRepository
     *
     * @author lord
     * 2025/9/5 23:34
     */
    @Bean
    @ConditionalOnMissingBean(HttpRetryTaskRepository.class)
    public HttpRetryTaskRepository taskRepository() {
        return new HttpRetryTaskMybatisRepository();
    }
}
